package study.kits.excel.easyexcel.controller;

import cn.hutool.core.date.StopWatch;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import study.kit.eggs.result.Result;
import study.kit.eggs.result.Results;

import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/bigData")
public class BigDataController {

    @PostMapping("/import")
    @ResponseBody
    public Result importExcel(@RequestParam MultipartFile file) throws Exception {
        InputStream in = file.getInputStream();

        StopWatch stopWatch = StopWatch.create("");
        stopWatch.start();
        EasyExcel.read(in,
                       SalesmanInfoData.class,
                       new SalesmanEventListener()).sheet().doRead();
        stopWatch.stop();

        log.info(">>>>>>>>>> {}", stopWatch.prettyPrint());
        return Results.ok();
    }

    class SalesmanEventListener extends AnalysisEventListener<SalesmanInfoData> {

        private List<SalesmanInfoData> dataLt = Lists.newArrayList();

        private int totalSize;

        @Override
        public void invoke(SalesmanInfoData data, AnalysisContext context) {
            totalSize++;
            dataLt.add(data);
            //save
            if (dataLt.size() >= 500) {
                log.info("执行一次处理");
                dataLt.clear();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            log.info(">>>>>>>>>> 解析完成: 共 {} 条，合法 {} 条", totalSize);
        }
    }

    @Data
    public class SalesmanInfoData implements Serializable {

        @ExcelProperty(index = 0)
        private String salesmanMobile;
        @ExcelProperty(index = 1)
        private String openId;
        @ExcelProperty(index = 2)
        private String nickName;
        @ExcelProperty(index = 3)
        private String grade;
        // 4
        @ExcelProperty(index = 5)
        private String invitedMobile;
        @ExcelProperty(index = 6)
        private String invitedOpenId;
        // 7
        @ExcelProperty(index = 8)
        private String teamName;
        @ExcelProperty(index = 9)
        private String salesmanCode;
        @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
        @ExcelProperty(index = 10)
        private Date joinTime;
        @ExcelProperty(index = 11)
        private Integer customerNum;
    }
}
